// Michael Depuy
// depuym@onid.orst.edu
// CS344-400
// Homework 6

#include "compute.h"
#include <sys/time.h>
#include <time.h>
#define PORT_NUM 9879
#define PORT_NUM_STR "9879"

int sockfd;
void handler(int arg){
  printf("Signal caught. Terminating");
  close(sockfd);
  exit(0);
}

// Function to compute how much time it takes to perform a function.
// NEEDS TO END AROUND 15 SECONDS
int compTime(){
  int i; //counter
  time_t t_before; //times
  time_t t_after; 
  time_t time_ops; 
  int ops; //operations
  ops = 0;
  time(&t_before);
  while(time_ops < 15){
    i = ops % 2;
    ops += 1;
    time(&t_after);
    time_ops = t_after - t_before;
  }
  return ops; 
}

// Main function to compute perfect numbers
/*int computePerfectNumbers(int range){
  int num,sum;
  int i,j;
  sum = 1;
  for(i=0; i<range; i++){
    if(
  }
  

  return 0;
}*/


int main(int argc, char **argv){

  int num_ops = 0;
  struct sockaddr_in server_addr;
  char time_info[32];
  char client_type;
  // Time mod operations
  num_ops = compTime();
  signal(SIGINT,handler);
  // Server information
  bzero(&server_addr, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(PORT_NUM);
  server_addr.sin_addr.s_addr = inet_addr(argv[1]);

  printf("Setting up socket...\n");
  // Setup socket
  sockfd = socket(AF_INET,SOCK_STREAM,0);
  client_type = '1';
  printf("Connecting.....\n");
  if(connect(sockfd,(struct sockaddr *)&server_addr, sizeof(server_addr)) < 0){
    printf("Error: Connection failed. Please try again.\n");
    exit(1);
  }
  
  // Do stuff
  snprintf(time_info,sizeof(time_info),"%d",num_ops);
  printf("did stuff \n");
  // Report results
  write(sockfd,&client_type,sizeof(char));
  write(sockfd,time_info,strlen(time_info));

  // Close socket
  close(sockfd);

  return 0;
}
